package com.xuzao.developer.controller;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.xuzao.developer.base.model.DevelopPlan;
import com.xuzao.developer.base.model.ProjectVersion;
import com.xuzao.developer.dao.ProjectVersionDao;
import com.xuzao.developer.dto.DevelopPlanDTO;
import com.xuzao.developer.enums.DevelopPlanStatusEnum;
import com.xuzao.developer.service.DevelopPlanService;
import com.xuzao.developer.utils.*;
import com.xuzao.developer.vo.DevelopPlanExportVO;
import com.xuzao.developer.vo.DevelopPlanVO;
import com.xuzao.developer.tools.entity.Pager;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author xuzao
 * @description
 * @date 2019-08-09 18:12:00
 **/
@Controller
@RequestMapping("/developPlan/")
public class DevelopPlanController {


    @Resource
    private DevelopPlanService developPlanService;
    @Resource
    private ProjectVersionDao projectVersionDao;

    @RequestMapping("queryList")
    public String queryList(DevelopPlanDTO dto, Pager pager, Model model) {
        List<ProjectVersion> projectVersionList = projectVersionDao.selectListAll();
        List<Map<String, Object>> projectList = Lists.newArrayList();
        if (!projectVersionList.isEmpty()) {
            projectVersionList.forEach(o -> {
                Map<String, Object> map = Maps.newHashMap();
                map.put("id", o.getId());
                map.put("name", o.getName());
                if (dto.getProjectId() != null && IntegerUtil.equalTo(dto.getProjectId(), o.getId())) {
                    map.put("selected", "selected");
                } else {
                    map.put("selected", "");
                }
                projectList.add(map);
            });

            if (dto.getProjectId() == null) {
                dto.setProjectId(projectVersionList.get(0).getId());
            }
        }
        List<Map<String, Object>> statusList = Lists.newArrayList();
        for (DevelopPlanStatusEnum value : DevelopPlanStatusEnum.values()) {
            Map<String, Object> map = Maps.newHashMap();
            map.put("id", value.getCode());
            map.put("name", value.getDesc());
            if (dto.getStatus() != null && IntegerUtil.equalTo(dto.getStatus(), value.getCode())) {
                map.put("selected", "selected");
            } else {
                map.put("selected", "");
            }
            statusList.add(map);
        }
        model.addAttribute("statusList", statusList);
        model.addAttribute("projectList", projectList);
        model.addAttribute("bo", dto);
        model.addAttribute("list", developPlanService.list(dto, pager));
        return "/develop_plan/develop_plan_list";
    }

    @RequestMapping("export")
    public void export(DevelopPlanDTO dto, HttpServletResponse response) {
        List<DevelopPlanVO> developPlanVOS = developPlanService.list(dto, null);

        List<String> rowNameList = Arrays.asList("系统", "任务模块", "功能描述", "业务场景/业务价值", "优先级", "状态",
                "每日进度", "开发责任人", "后端开发时间", "开发完成日期", "实际开发时间", "开发联调日期", "前端负责人", "前端开发时间", "实际联调时间", "提测时间", "测试负责人", "测试时间", "测试完成日期", "实际测试时间");

        List<Object[]> objects = new ArrayList<>();
        String[] rowName = (String[]) rowNameList.toArray();
        for (DevelopPlanVO item : developPlanVOS) {
            DevelopPlanExportVO developPlanExportVO = new DevelopPlanExportVO();
            BeanUtils.copyProperties(item, developPlanExportVO);
            objects.add(ReflectUtils.getAllFieldValues(developPlanExportVO, rowName.length));
        }
        HSSFWorkbook workbook = new HSSFWorkbook();
        ExcelUtils.export("仓配一体开发进度表", rowName, objects, ExcelUtils.getTitleStyleForDevelop(workbook), ExcelUtils.getCellStypeForDevelop(workbook), workbook, response);
    }

    @RequestMapping("add")
    public String add(Model model) {
        List<ProjectVersion> projectVersionList = projectVersionDao.selectListAll();
        DevelopPlan bo = new DevelopPlan();
        model.addAttribute("bo", bo);
        model.addAttribute("list", projectVersionList);
        return "/develop_plan/develop_plan_add";
    }

    @RequestMapping("update")
    public String update(Model model, Long id, HttpServletRequest request, HttpServletResponse response) {
        String key = "develop_update" + "_" + id;
        String uuidc = CookieUtil.getCookie(request, key);
        Object deve = RedisUtil.get(key);

        System.out.println("getInfo==>" + uuidc + " , " + deve);

        if (StringUtils.isBlank(uuidc) && deve !=null) {
            return "/develop_plan/develop_warnning";
        } else if (StringUtils.isNotBlank(uuidc) && deve != null) {
            if (IntegerUtil.notEqualTo(deve.toString(), uuidc)) {
                return "/develop_plan/develop_warnning";
            }
        }

        String uuid = UUIDUtils.generateShortUuid();
        CookieUtil.setCookie(response, key, uuid);

        System.out.println("setInfo==>" + uuid);

        RedisUtil.remove(key);
        RedisUtil.setnx(key, uuid, 180);


        DevelopPlanDTO bo = new DevelopPlanDTO();
        bo.setId(id);
        model.addAttribute("bo", developPlanService.get(bo));
        return "/develop_plan/develop_plan_update";
    }

    @RequestMapping("save")
    @ResponseBody
    public BJUIMap save(DevelopPlanDTO dto, HttpServletResponse response, HttpServletRequest request) {
        BJUIMap map = new BJUIMap();
        map.setMessage("操作成功");
        map.setTabid("developPlan");
        map.setCloseCurrent(BJUIMap.CALLBACK_CLOSE);
        map.setStatusCode(BJUIMap.CODE_OK);

        if (StringUtils.isNotBlank(dto.getFlag())) {
            DevelopPlanDTO update = new DevelopPlanDTO();
            update.setId(dto.getId());
            update.setStatus(dto.getStatus());
            update.setDayRate(dto.getDayRate());
            update.setJavaDeveActualTime(dto.getJavaDeveActualTime());
            update.setShowJointDebugTime(dto.getShowJointDebugTime());
            update.setWebDeveTime(dto.getWebDeveTime());
            update.setJointDebugActualTime(dto.getJointDebugActualTime());
            update.setShowTestStartTime(dto.getShowTestStartTime());
            update.setShowTestFinishTime(dto.getShowTestFinishTime());
            update.setTestTime(dto.getTestTime());
            update.setTestActualTime(dto.getTestActualTime());
            update.setRisk(dto.getRisk());
            update.setRemarks(dto.getRemarks());
            update.setSystemName(dto.getSystemName());


            String key = "develop_update" + "_" + dto.getId();
            String uuidc = CookieUtil.getCookie(request, key);
            Object deve = RedisUtil.get(key);

            System.out.println("getInfo==>" + uuidc + " , " + deve);
            if (deve != null && uuidc != null) {
                if (IntegerUtil.equalTo(deve.toString(), uuidc)) {
                    RedisUtil.remove(key);
                    CookieUtil.setCookie(response, key, "");
                    developPlanService.update(dto);
                    return map;
                }
            }
            map.setMessage("数据已过期，请退出重试");
            map.setStatusCode(BJUIMap.CODE_ERROR);
            return map;
        } else {
            developPlanService.insert(dto);
        }


        return map;
    }

    @RequestMapping("cancel")
    @ResponseBody
    public BJUIMap cancel(Long id, HttpServletRequest request, HttpServletResponse response) {
        BJUIMap map = new BJUIMap();
        map.setMessage("操作已取消");
        map.setTabid("developPlan");
        map.setCloseCurrent(BJUIMap.CALLBACK_CLOSE);
        map.setStatusCode(BJUIMap.CODE_OK);

        String key = "develop_update" + "_" + id;
        String uuidc = CookieUtil.getCookie(request, key);
        Object deve = RedisUtil.get(key);

        System.out.println("getInfo==>" + uuidc + " , " + deve);
        if (deve != null && uuidc != null) {
            if (IntegerUtil.equalTo(deve.toString(), uuidc)) {
                RedisUtil.remove(key);
                CookieUtil.setCookie(response, key, "");
            }
        }


        return map;
    }

    @RequestMapping("del")
    @ResponseBody
    public BJUIMap del(DevelopPlanDTO dto) {
        developPlanService.del(dto.getId());
        BJUIMap map = new BJUIMap();
        map.setMessage("操作成功");
        map.setTabid("developPlan");
        map.setStatusCode(BJUIMap.CODE_OK);
        return map;
    }

    @RequestMapping("import")
    public String importExcel(Model model) {
        List<ProjectVersion> projectVersionList = projectVersionDao.selectListAll();
        model.addAttribute("list", projectVersionList);
        return "/develop_plan/develop_plan_import";
    }

    @RequestMapping("importSave")
    @ResponseBody
    public BJUIMap importSave(Long projectId, @RequestParam("file") MultipartFile file) {
        Workbook workbook = ExcelUtils.getExcelInfo(file);
        Sheet developSheet = workbook.getSheetAt(0);
        List<DevelopPlanDTO> developPlanDTOS = Lists.newArrayList();
        // 循环Excel行数
        for (Row row : developSheet) {
            //首行跳过
            int rowNum = row.getRowNum();
            if (rowNum >= 1) {
                DevelopPlanDTO bean = new DevelopPlanDTO();
                for (Cell cell : row) {
                    if (null != cell) {
                        cell.setCellType(CellType.STRING);
                        Object o = cell.getStringCellValue();
                        String str = String.valueOf(o).trim();
                        if (cell.getColumnIndex() == 0) {
                            bean.setSystemName(isCombineCell(getCombineCellList(developSheet), cell, developSheet));
                            continue;
                        }
                        if (cell.getColumnIndex() == 1) {
                            bean.setModelName(isCombineCell(getCombineCellList(developSheet), cell, developSheet));
                            continue;
                        }
                        if (cell.getColumnIndex() == 2) {
                            bean.setModelDesc(str);
                            continue;
                        }
                        if (cell.getColumnIndex() == 3) {
                            bean.setModelWorth(isCombineCell(getCombineCellList(developSheet), cell, developSheet));
                            continue;
                        }
                        if (cell.getColumnIndex() == 4) {
                            if (StringUtils.isNotBlank(str)) {
                                bean.setLevel(Integer.valueOf(str));
                            }
                            continue;
                        }
                        if (cell.getColumnIndex() == 5) {
                            if (StringUtils.isNotBlank(str)) {
                                bean.setStatus(DevelopPlanStatusEnum.valueOf(str).getCode());
                            } else {
                                bean.setStatus(DevelopPlanStatusEnum.init.getCode());
                            }
                            continue;
                        }
                        if (cell.getColumnIndex() == 6) {
                            if (StringUtils.isNotBlank(str)) {
                                bean.setDayRate(Integer.valueOf(str));
                            }
                            continue;
                        }
                        if (cell.getColumnIndex() == 7) {
                            bean.setJavaer(str);
                            continue;
                        }
                        if (cell.getColumnIndex() == 8) {
                            if (StringUtils.isNotBlank(str)) {
                                bean.setJavaDeveTime(Integer.valueOf(str));
                            }
                            continue;
                        }
                        if (cell.getColumnIndex() == 9) {
                            bean.setShowJavaDeveFinishTime(str);
                            continue;
                        }
                        if (cell.getColumnIndex() == 10) {
                            if (StringUtils.isNotBlank(str)) {
                                bean.setJavaDeveActualTime(Integer.valueOf(str));
                            }
                            continue;
                        }
                        if (cell.getColumnIndex() == 11) {
                            if (StringUtils.isNotBlank(str)) {
                                bean.setShowJointDebugTime(str);
                            }
                            continue;
                        }
                        if (cell.getColumnIndex() == 12) {
                            if (StringUtils.isNotBlank(str)) {
                                bean.setWeber(str);
                            }
                            continue;
                        }
                        if (cell.getColumnIndex() == 13) {
                            if (StringUtils.isNotBlank(str)) {
                                bean.setWebDeveTime(Integer.valueOf(str));
                            }
                            continue;
                        }
                        if (cell.getColumnIndex() == 14) {
                            if (StringUtils.isNotBlank(str)) {
                                bean.setJointDebugActualTime(Integer.valueOf(str));
                            }
                            continue;
                        }
                        if (cell.getColumnIndex() == 15) {
                            if (StringUtils.isNotBlank(str)) {
                                bean.setShowTestStartTime(str);
                            }
                            continue;
                        }
                        if (cell.getColumnIndex() == 16) {
                            bean.setTester(str);
                        }
                        if (cell.getColumnIndex() == 17) {
                            if (StringUtils.isNotBlank(str)) {
                                bean.setTestTime(Integer.valueOf(str));
                            }
                            continue;
                        }
                        if (cell.getColumnIndex() == 18) {
                            bean.setShowTestFinishTime(str);
                        }
                        if (cell.getColumnIndex() == 19) {
                            if (StringUtils.isNotBlank(str)) {
                                bean.setTestActualTime(Integer.valueOf(str));
                            }
                            continue;
                        }
                    }
                }
                bean.setProjectId(projectId);
                if (StringUtils.isNotBlank(bean.getSystemName())) {
                    developPlanDTOS.add(bean);
                }
            }
        }
        developPlanService.insertByList(developPlanDTOS);
        BJUIMap map = new BJUIMap();
        map.setMessage("操作成功");
        map.setTabid("developPlan");
        map.setStatusCode(BJUIMap.CODE_OK);
        return map;
    }


    public String isCombineCell(List<CellRangeAddress> listCombineCell, Cell cell, Sheet sheet) {
        int firstC = 0;
        int lastC = 0;
        int firstR = 0;
        int lastR = 0;
        String cellValue = null;
        for (CellRangeAddress ca : listCombineCell) {
            //获得合并单元格的起始行, 结束行, 起始列, 结束列
            firstC = ca.getFirstColumn();
            lastC = ca.getLastColumn();
            firstR = ca.getFirstRow();
            lastR = ca.getLastRow();
            if (cell.getRowIndex() >= firstR && cell.getRowIndex() <= lastR) {
                if (cell.getColumnIndex() >= firstC && cell.getColumnIndex() <= lastC) {
                    Row fRow = sheet.getRow(firstR);
                    Cell fCell = fRow.getCell(firstC);
                    cellValue = getCellValue(fCell);
                    break;
                }
            } else {
                cellValue = cell.getStringCellValue();
            }
        }
        return cellValue;
    }

    public String getCellValue(Cell cell) {
        if (cell == null) {
            return "";
        }
        return cell.getStringCellValue();
    }

    //获取合并单元格集合
    public static List<CellRangeAddress> getCombineCellList(Sheet sheet) {
        List<CellRangeAddress> list = new ArrayList<>();
        //获得一个 sheet 中合并单元格的数量
        int sheetmergerCount = sheet.getNumMergedRegions();
        //遍历所有的合并单元格
        for (int i = 0; i < sheetmergerCount; i++) {
            //获得合并单元格保存进list中
            CellRangeAddress ca = sheet.getMergedRegion(i);
            list.add(ca);
        }
        return list;
    }

}